<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="年级" prop="noticeType">
        <el-select v-model="queryParams.greadNumber" placeholder="请选择年级" clearable>
          <el-option
            v-for="dict in dict.type.sys_grade_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <template v-if="userType === '4'">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:claass:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:claass:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
      </el-row>
    </template>
    <el-table v-loading="loading" :data="claassList" @selection-change="handleSelectionChange">
      <template v-if="userType === '4'">
        <el-table-column type="selection" width="55" align="center" />
      </template>
      <el-table-column label="年级" align="center" prop="greadNumber" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_grade_type" :value="scope.row.greadNumber"/>
        </template>
      </el-table-column>
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班级课程" align="center" prop="courseNames"/>
      <template v-if="userType === '4'">
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:claass:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:claass:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改班级用户班级和课程进行关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="年级">
          <el-select v-model="form.greadNumber">
            <el-option
              v-for="dict in dict.type.sys_grade_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="科目类别" prop="courseId">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="form.courseId" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in subjectList" :label="item.id" :key="item.id">
              {{ item.courseName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClaass, getClaass, delClaass, addClaass, updateClaass } from "@/api/system/claass";
import { listType } from "@/api/system/courseType";
import {listUser} from "@/api/system/user";

export default {
  name: "Claass",
  dicts: ['sys_grade_type','sys_course_design_type'],
  data() {
    return {
      checkAll: false,
      isIndeterminate: true,
      teacherList: [],
      subjectList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级用户班级和课程进行关联表格数据
      claassList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        greadNumber: null,
        classNumber: null,
        className: null,
        courseId: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      userType: '',
    };
  },
  created() {
    this.getList();
    this.userType = localStorage.getItem('userType')
  },
  methods: {
    handleCheckAllChange(val) {
      this.form.courseId = val ? this.subjectList.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    /** 查询班级用户班级和课程进行关联列表 */
    getList() {
      this.loading = true;
      listClaass(this.queryParams).then(response => {
        this.claassList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        greadNumber: null,
        classNumber: null,
        className: null,
        createTime: null,
        updateTime: null,
        courseId: [],
        classManagerUserId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.subjectList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.subjectList.length;
    },
    getSubjectList() {
      listType({
        pageNum: 1,
        pageSize: 100,
      }).then(res => {
        this.subjectList = res.rows
        this.checkAll = this.form.courseId?.length === this.subjectList.length
        this.isIndeterminate = false
        listUser({
          pageNum: 1,
          pageSize: 100,
          postIds: 1,
          startPage: false
        }).then(result => {
          this.open = true;
          this.teacherList = result.rows
        })
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加班级"
      this.getSubjectList()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getClaass(id).then(response => {
        this.form = {
          ...response.data,
          courseId: response.data.courseId.split(',')
        }

        this.title = "修改班级信息"
        this.getSubjectList()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const params = {
            ...this.form,
            courseId: this.form.courseId.join(',')
          }
          if (this.form.id != null) {
            updateClaass(params).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            addClaass(params).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除【${row.className}】的数据？`).then(function() {
        return delClaass(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/claass/export', {
        ...this.queryParams
      }, `claass_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
